<?php

namespace app\controllers\supplier\base;

use app\controllers\Controller;
use Firebase\JWT\JWT;
use Yii;

/**
 * Class AdminController
 * @package app\controllers\admin\base
 */
class AdminController extends Controller
{
    use Constant;

    protected $user;

    public function beforeAction($action)
    {
        if (! parent::beforeAction($action)) {
            return false;
        }

        $token = Yii::$app->getRequest()->getHeaders()->get(Yii::$app->params['SUPPLIER_TOKEN']);
        $white_list = require __DIR__ . '/../config/white_list.php';
        $url = $action->getUniqueId();
        $url = substr($url, strlen('supplier'));

        if (!in_array($url, $white_list)) {
            $key = Yii::$app->params['JWT_SUPPLIER_KEY'];
            if ($this->jwtAuthentication($token, $key)) {
                return true;
            } else {
                Yii::$app->getResponse()->data = $this->fail('登录过期,请重新登录', Yii::$app->params['CODE_TOKEN_EXPIRED']);
                return false;
            }
        }

        return true;
    }

    private function jwtAuthentication($authorization, $key)
    {
        try {
            // 时间
            JWT::$leeway = 60;
            $decode = JWT::decode($authorization, $key, ['HS256']);
            $this->user = $decode->data;
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
}